﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace PmfWeb.Core.Forms
{
    /// <summary>
    /// web请求类(HttpRequest)
    /// </summary>
    public class WebPost
    {
        ///<summary>
        /// 跨域POST方式提交表单信息
        ///</summary>
        ///<param name="postUrl">要提交的处理页地址</param>
        ///<param name="postParas">参数</param>
        ///<returns></returns>
        public static string Post(string postUrl, string postParas)
        {
            string result = "";
            try
            {
                Encoding encode = Encoding.GetEncoding("utf-8");
                Uri uri = new Uri(postUrl);
                byte[] parasBytes = encode.GetBytes(postParas);

                WebRequest request = WebRequest.Create(uri);
                request.Timeout = 60000;
                request.ContentType = "application/x-www-form-urlencoded,charset=utf-8";
                request.Method = EnumMethod.POST.ToString();
                using (Stream stream = request.GetRequestStream())
                {
                    //发送数据
                    stream.Write(parasBytes,0,parasBytes.Length);
                }
                WebResponse response = request.GetResponse();

                using (StreamReader reader = new StreamReader(response.GetResponseStream(),encode))
                {
                    result = reader.ReadToEnd();
                }
                return result;

            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        public static string Get(string getUrl, string getParas)
        {
            string result = "";
            try
            {
                Encoding encode = Encoding.GetEncoding("utf-8");
                Uri uri = new Uri(String.Format("{0}?{1}", getUrl, getParas));
                WebRequest request = WebRequest.Create(getUrl);
                request.Timeout = 60000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = EnumMethod.GET.ToString();
                WebResponse response = request.GetResponse();

                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encode))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }


        ///<summary>
        /// 方法类型枚举
        ///</summary>
        public enum EnumMethod
        {
            ///<summary>
            /// POST传值
            ///</summary>
            POST = 0,
            /// <summary>
            /// Get方式传值
            /// </summary>
            GET =1
        }
    }
}
